/**
* 真实连网函数入口
*/
import qs from "qs";
import { SERVICE_URL, REQ_TIMEOUT } from '../configs/index';
import { Actions } from 'react-native-router-flux';

// 生成可用url
const service_url = (path) => {
  return SERVICE_URL + path
}
// http 类型定义
const http_post = http_factory({ method: "POST", paramsType: "form" })
const http_get = http_factory({ method: "GET", paramsType: "query" })
const http_post_file = http_factory({ method: "POST", paramsType: "file" })
function http_factory({ method, paramsType }) {
  return async (path, params) => {
    /** 形成service头和数据包 */
    const meta = {
      method: method,
      timeout: REQ_TIMEOUT,
      headers: {

      },
    }
    switch (paramsType) {
      case 'form':
        meta.headers['Content-type'] = 'application/json';
        meta.headers['Accept'] = 'application/json';
        if (path == (SERVICE_URL + "api/user/bankcard/delete")) {
          path = SERVICE_URL + "api/user/bankcard/delete" + '/' + params.id
          meta.body = JSON.stringify(params)
        } else {
          meta.body = JSON.stringify(params);
        }
        break;
      case 'file':
        meta.headers['Content-type'] = 'multipart/form-data';
        meta.body = getFormData(params);
        break;
      default:
        const query = qs.stringify(params)
        if (query) path += `?${query}`
    }
    /** 开始连网获并取返回数据 */
    console.log('%c service_helpers ## path: ## ' + path + ' ## meta -->> ', 'color:limegreen', meta);
    try {
      const response = await fetch(path, meta);
      console.log('%c service_helpers resopnse-stauts -->> ', 'color:limegreen', response.status);
      if (response.status == 200) {
        const text = await response.text()
        const jsonData = JSON.parse(text)
        console.log('%c service_helpers response-jsonData -->> ', 'color:limegreen', jsonData);
        let code = jsonData.failedCode;
        let status = jsonData.status

        if (status == "success") {
          return { success: true, data: jsonData.data };
        } else {
          if(jsonData.failedCode === 'NO_LOGIN'){
            
          }
          return { success: false, code: code, message: jsonData.failedMsg }
        }
      } else {
        return { success: false, code: response.status, message: '网络连接异常' };
      }
    } catch (ex) {
      console.log('%c service_helpers fetch error -->> ', 'color:red', ex);
      return { success: false, code: 400, message: "网络连接异常" };
    }
  }
}
function getFormData(params) {
  const f = new window.FormData()
  let pp = params.photo
  if (isArray(pp)) {
    for (let i = 0; i < pp.length; i++) {
      let p = pp[i];
      for (let key in p) {
        if (p.hasOwnProperty(key)) {
          f.append(key, p[key])
        }
      }
    }
  } else {
    for (let key in params) {
      if (params.hasOwnProperty(key)) {
        f.append(key, params[key])
      }
    }
  }
  return f
}

function isArray(obj) {
  if (Array.isArray) {
    return Array.isArray(obj);
  } else {
    return Object.prototype.toString.call(obj) === "[object Array]";
  }
}

export { http_get, http_post, http_post_file, service_url }
